import axios from "@/util/axios";
import Vue from "vue";
import VueRouter from "vue-router";
import $store from "../store/index.js";
import routers from "./router";
import ViewUI from 'view-design'
import Util from '../libs/util'

Vue.use(VueRouter);
// 路由配置
const RouterConfig = {
  mode: "history",
  routes: [routers]
};
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};
export const router = new VueRouter(RouterConfig);

var queryToken = location.href.substring().indexOf("token"); // 查询参数有token一定会重新获取菜单
var menusPath = [];

var path = "";
if (queryToken != -1) {
  var herf = location.href;
  var startIndex = herf.indexOf("?");
  var querystring = herf.substring(startIndex + 1);
  var url = herf.substring(0, startIndex);
  var parms = [];
  querystring.split("&").forEach(x => {
    var eleT = x.split("=");
    parms.push({
      key: eleT[0],
      value: eleT[1]
    });
  });

  if (
    parms.findIndex(x => x.key == "appId") != -1 &&
    parms.findIndex(x => x.key == "token") != -1
  ) {
    console.log("参数")
    localStorage.setItem("token", parms.find(x => x.key == "token").value);
    // localStorage.setItem("appId", parms.find(x => x.key == "appId").value);
    axios({
      method: "GET",
      url: decodeURIComponent(parms.find(x => x.key == "config").value)
    }).then(res => {
      var config = res.data;
      localStorage.setItem("config", JSON.stringify(config));
      var menuRoot = parms.find(x => x.key == "appId").value;

      axios({
        baseURL: config.tyrz,
        method: "GET",
        url: `/menu/${menuRoot}`,
      }).then(res2 => {
        var result = res2.data;
        $store.commit("setMenuRoot", result.info);
        $store.commit("setUseInfo", result.user);

        $store.commit("setMenus", result.menus);
        var menus = $store.state.app.menuList;
        console.log(JSON.stringify(menus));
        if (!menus || menus.length == 0) {
          alert("未获取到菜单，无权限或localStorage存储异常");
          return;
        }
        if (!menus[0].children || menus[0].children.length == 0) {
          alert("未获取到菜单子项");
          return;
        }


        if (path == "" || path == `${process.env.VUE_APP_VIRTUAL_PATH}/`) {
          path = menus[0].children[0].path;
        }

        console.log(`path:${path}`)

        if (!path) {
          alert("菜单项路径为空");
          return;
        }
        menus.forEach(x => {
          x.children.forEach(x2 => {
            menusPath.push(x2.path);
          });
        });

        $store.commit("setCurrentPaths", path);
        router.push({
          path: path
        });


      });
    });
  }
} else {

  setTimeout(() => {

    // var menus = $store.state.app.menuList;
    // if (!menus || menus.length == 0) {
    //   alert("获取用户信息失败，请重新登录");
    // }
    // console.log("path:" + path)
    // if (path == "" || path == `${process.env.VUE_APP_VIRTUAL_PATH}/`) {
    //   path = menus[0].children[0].path;
    // }
    // // let path = $store.state.app.menuList[0].children[0].path;
    // menus.forEach(x => {
    //   x.children.forEach(x2 => {
    //     menusPath.push(x2.path);
    //   });
    // });
    // $store.commit("setCurrentPaths", path);
    // router.push({
    //   path: path
    // });
  }, 100);
}

router.beforeEach((to, from, next) => {
  // ViewUI.LoadingBar.start()
  // var name = $store.state.app.menuRoot.name
  // Util.title(name)
  // path = to.path;
  // next();
  // if (menusPath.length) {
  //   console.log(`toPath:${to.path}`);
  //   //路由拦截
  //   let Permission = to.path;
  //   let exist = menusPath.findIndex(x => x == Permission);
  //   console.log(`exist:${exist}`);
  //   if (exist != -1) {
  //     next();
  //   } else {
  //     next(false);
  //   }
  // } else {
  //   console.log(`to2Path:${to.path}`);
  //   let path = to.path;
  //   var menus = $store.state.app.menuList;
  //   menus.forEach(x => {
  //     x.children.forEach(x2 => {
  //       menusPath.push(x2.path);
  //     });
  //   });
  //   $store.commit("setCurrentPaths", path);
  //   router.push({
  //     path: path
  //   });
  //   next(false);
  // }
  next();
});

router.afterEach((to, from, next) => {
  ViewUI.LoadingBar.finish()

})